package com.song.flowable.common;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.song.flowable.view.vo.ModelResponse;
import org.flowable.engine.FormService;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.repository.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ResponseFactory {
	private final IdentityService identityService;
	private final FormService formService;
	private final HistoryService historyService;
	private final ObjectMapper objectMapper;

	@Autowired
	public ResponseFactory(IdentityService identityService, FormService formService, HistoryService historyService, ObjectMapper objectMapper) {
		this.identityService = identityService;
		this.formService = formService;
		this.historyService = historyService;
		this.objectMapper = objectMapper;
	}

	public ModelResponse createModelResponse(Model model) {
		ModelResponse response = new ModelResponse();
		response.setCategory(model.getCategory());
		response.setCreateTime(model.getCreateTime());
		response.setId(model.getId());
		response.setKey(model.getKey());
		response.setLastUpdateTime(model.getLastUpdateTime());
		response.setDeploymentId(model.getDeploymentId());
		response.setHasEditorSource(model.hasEditorSource());
		response.setName(model.getName());
		response.setVersion(model.getVersion());
		response.setTenantId(model.getTenantId());
		try {
			JsonNode modelNode = objectMapper.readTree(model.getMetaInfo());
			if(modelNode.get("description") != null){
				response.setDescription(modelNode.get("description").asText());
			}
			if(modelNode.get("modelState") != null){
				response.setModelState(modelNode.get("modelState").asBoolean());
			}
			if(modelNode.get("warningRequestUrl") != null){
				response.setWarningRequestUrl(modelNode.get("warningRequestUrl").asText());
			}
			if(modelNode.get("endUrl") != null){
				response.setEndUrl(modelNode.get("endUrl").asText());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (model.getDeploymentId() != null) {
			response.setDeployed(true);
		} else {
			response.setDeployed(false);
		}
		return response;
	}
}
